﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Urs.Admin.Models.Coupons;
using Urs.Admin.Models.Users;
using Urs.Core;
using Urs.Data.Domain.Users;
using Urs.Data.Domain.Orders;
using Urs.Data.Domain.Configuration;
using Urs.Data.Domain.Coupons;
using Urs.Services.Coupons;
using Urs.Services.Users;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Orders;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Extensions;
using Urs.Framework.Kendoui;
using Urs.Framework.Mvc;
using Urs.Web.Infrastructure;

namespace Urs.Admin.Controllers
{
    public class CouponController : BaseAdminController
    {

        #region Field
        private readonly IWorkContext _workContext;
        private readonly ICouponService _couponService;
        private readonly IPermissionService _permissionService;
        private readonly IUserService _userService;
        private readonly IPictureService _pictureService;
        private readonly IOrderService _orderService;
        private readonly ILocalizationService _localizationService;
        private readonly UserSettings _userSettings;
        private readonly StoreInformationSettings _storeInformationSettings;
        #endregion

        #region constuctor
        public CouponController(IWorkContext workContext, ICouponService couponService,
            IPermissionService permissionService,
            IUserService userService,
            IPictureService pictureService,
            IOrderService orderService,
            ILocalizationService localizationService,
            UserSettings userSettings,
            StoreInformationSettings storeInformationSettings)
        {
            this._workContext = workContext;
            this._couponService = couponService;
            this._permissionService = permissionService;
            this._userService = userService;
            this._pictureService = pictureService;
            this._orderService = orderService;
            this._localizationService = localizationService;
            this._userService = userService;
            this._userSettings = userSettings;
            this._storeInformationSettings = storeInformationSettings;
        }

        #endregion

        #region Utility

        [NonAction]
        protected string GetUserRolesNames(IList<UserRole> userRoles, string separator = ",")
        {
            var sb = new StringBuilder();
            for (int i = 0; i < userRoles.Count; i++)
            {
                sb.Append(userRoles[i].Name);
                if (i != userRoles.Count - 1)
                {
                    sb.Append(separator);
                    sb.Append(" ");
                }
            }
            return sb.ToString();
        }

        [NonAction]
        protected UserModel PrepareUserModelForList(User user)
        {
            return new UserModel()
            {
                Id = user.Id,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                FullName = user.GetFullName(),
                SystemRoleNames = GetUserRolesNames(user.UserRoles.ToList()),
                LastIpAddress = user.LastIpAddress,
                Active = user.Active,
                CreateTime = user.CreateTime,
                LastActivityDate = user.LastActivityTime,
            };
        }

        #endregion

        #region 优惠券增查
        public IActionResult List(PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var model = new CouponListModel();

            return View(model);
        }
        [HttpPost]
        public IActionResult ListJson(CouponListModel list, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var user = _workContext.CurrentUser;

            var coupons = _couponService.GetCoupon(list.StartTime, list.EndTime, null, command.Page - 1, command.Limit);
            var result = new ResponseResult();

            result.data = coupons.Select(x =>
            {
                var model = new CouponModel();
                model.Id = x.Id;
                model.Title = x.Title;
                model.StartTime = x.StartTime;
                model.EndTime = x.EndTime;
                model.MinimumConsumption = x.MinimumConsumption;
                model.Value = x.Value;
                model.Amount = x.Amount;
                model.UsedAmount = x.UsedAmount;
                model.IsAmountLimit = x.IsAmountLimit;
                return model;
            });
            result.count = coupons.TotalCount;

            return Json(result);
        }

        public IActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();
            var coupon = _couponService.GetCouponById(id);
            var model = new CouponModel();
            var user = _workContext.CurrentUser;      //判断商户是否一致
            if (coupon == null)
            {
                return View(model);
            }
            else
            {
                model = coupon.ToModel<CouponModel>();
                model.Url = string.Format("{0}ecardbind/{1}", _storeInformationSettings.StoreUrl, id);
            }
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(CouponModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();
            var coupon = _couponService.GetCouponById(model.Id);
            if (coupon == null)
            {
                coupon = new Coupon();
                coupon.Title = model.Title;
                coupon.Value = model.Value;
                coupon.StartTime = model.StartTime;
                coupon.EndTime = model.EndTime;
                coupon.MinimumConsumption = model.MinimumConsumption;
                coupon.IsAmountLimit = model.IsAmountLimit;
                coupon.Amount = model.Amount;
                coupon.UsedAmount = 0;
                _couponService.InsertCoupon(coupon);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    coupon = model.ToEntity(coupon);
                    _couponService.UpdateCoupon(coupon);
                }
                else
                    return Json(new { error = 1, msg = ModelState.FirstMessage() });
            }
            return Json(new { success = 1 });
        }

        [HttpPost]
        public IActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var coupon = _couponService.GetCouponById(id);
            if (coupon == null)
                //No news item found with the specified id
                return RedirectToAction("List");

            _couponService.DeleteCoupon(coupon);
            return RedirectToAction("List");
        }

        public IActionResult RandomNum()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            string num = "";
            string all = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            Random random = new Random();
            for (int i = 0; i < 9; i++)
            {
                int rd = random.Next(36);
                string oneChar = all.Substring(rd, 1);
                num += oneChar;
            }
            return Json(new { result = num });
        }
        public IActionResult CouponBinding(int id, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var coupon = new CouponModel();
            coupon.Id = id;
            return View(coupon);
        }
        [HttpPost]
        public IActionResult CouponBindingJson(CouponModel model, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var man = _couponService.GetCouponsOrUser(null, null, model.Id, command.Page - 1, command.Limit);

            var result = new ResponseResult();
            result.data = man.Select(x =>
            {
                var CreateTime = x.CreateTime.ToString("yyyy/MM/dd HH:mm:ss");
                var UsedTime = x.UsedTime.HasValue ? x.UsedTime.Value.ToString("yyyy/MM/dd HH:mm:ss") : string.Empty;

                return new { x.Id, x.User.Nickname, CreateTime, UsedTime, x.UserId };
            });
            result.count = man.TotalCount;

            return Json(result);
        }

        public IActionResult CouponBindingDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var cc = _couponService.GetCouponUserById(id);
            if (cc != null)
                _couponService.DeleteCouponUser(cc);

            return new NullJsonResult();
        }
        #endregion

        #region 发放卡卷
        public IActionResult SendCoupon()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var model = new SendCouponModel();
            var user = _workContext.CurrentUser;
            var coupons = _couponService.GetCoupon(null, null, null, 0, int.MaxValue);
            foreach (var item in coupons)
            {
                // model.List.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Title + "  " + "抵扣金额：" + PriceFormatter.FormatPrice(item.Value) });
            }
            return View(model);
        }

        public IActionResult SendCouponJson(PageRequest command)
        {
            if (_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var user = _workContext.CurrentUser;
            int[] searchUserRoleIds = new int[1] { _userService.GetUserRoleBySystemName(SystemRoleNames.Registered).Id };


            var users = _userService.GetAllUsers(userRoleIds: searchUserRoleIds,
                pageIndex: command.Page - 1, pageSize: command.Limit);

            var result = new ResponseResult
            {
                data = users.Select(x =>
                {
                    var list = new SendCouponModel();
                    list.Id = x.Id;
                    list.Username = x.GetFullName();
                    list.PictureUrl = _pictureService.GetPictureUrl(x.AvatarPictureId, 50);
                    var order = _orderService.SearchOrders(userId: x.Id, os: OrderStatus.Complete);
                    list.ConsumnCount = order.Count();
                    list.ConsumnMoney = order.Sum(a => a.OrderTotal);
                    return list;
                }),
                count = users.TotalCount,
            };
            return Json(result);
        }

        #endregion

        #region 优惠券派送

        public IActionResult AddUserCouponPopup(int couponId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var defaultRoleIds = new List<int> { _userService.GetUserRoleBySystemName(SystemRoleNames.Registered).Id };
            var listModel = new CouponModel.AddUserBindingModel()
            {
                SearchUserRoleIds = defaultRoleIds,
                CouponId = couponId
            };
            var allRoles = _userService.GetAllUserRoles(true);
            foreach (var role in allRoles)
            {
                listModel.AvailableUserRoles.Add(new SelectListItem
                {
                    Text = role.Name,
                    Value = role.Id.ToString(),
                    Selected = defaultRoleIds.Any(x => x == role.Id)
                });
            }
            return View(listModel);
        }

        [HttpPost]
        public IActionResult AddUserCouponPopupList(PageRequest command, CouponModel.AddUserBindingModel model, int[] searchUserRoleIds)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            var users = _userService.GetAllUsers(userRoleIds: searchUserRoleIds, email: model.SearchEmail, nickname: model.SearchUsername,
               phone: model.SearchPhone, pageIndex: command.Page - 1, pageSize: command.Limit);
            var result = new ResponseResult
            {
                data = users.Select(PrepareUserModelForList),
                count = users.TotalCount
            };

            return Json(result);
        }

        [HttpPost]
        [FormValueRequired("save")]
        public IActionResult AddUserCouponPopup(string btnId, string formId, CouponModel.AddUserBindingModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCoupons))
                return HttpUnauthorized();

            if (model.SelectedUserIds != null)
            {
                foreach (int id in model.SelectedUserIds)
                {
                    var user = _userService.GetUserById(id);

                    if (user != null && user.Active)
                    {
                        var cclist = _couponService.GetCouponsOrUser(user.Id, null, model.CouponId, 0, 1);
                        if (cclist.Count > 0) continue;

                        var userCoupon = new CouponUserMapping();
                        userCoupon.CouponId = model.CouponId;
                        userCoupon.UserId = id;
                        userCoupon.CreateTime = DateTime.Now;
                        _couponService.InsertCouponUser(userCoupon);
                    }
                }
            }

            ViewBag.RefreshPage = true;
            ViewBag.btnId = btnId;
            ViewBag.formId = formId;
            return View(model);
        }

        #endregion

        #region  查看用户的优惠卷
        public IActionResult CouponsBelonged(int Id)
        {
            var model = new CouponListModel();
            model.Id = Id;   //用户Id

            return View(model);
        }

        [HttpPost]
        public IActionResult CouponsBelonged(int manId, PageRequest command)
        {
            var user = _workContext.CurrentUser;

            var coupons = _couponService.GetCouponsOrUser(manId, null, null, command.Page - 1, command.Limit);

            var result = new ResponseResult();

            result.data = coupons.Select(x =>
            {
                var model = new CouponModel();
                var a = _couponService.GetCouponById(x.CouponId);
                model.Id = a.Id;  //优惠卷id
                                  //  model.Title = a.Title;
                model.StartTime = a.StartTime;
                model.EndTime = a.EndTime;
                model.Value = a.Value;
                model.GotTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                model.IsUsed = x.IsUsed ? "已使用" : "未使用";
                model.UsedTime = x.IsUsed ? ((DateTime)x.UsedTime).ToString("yyyy-MM-dd HH:mm:ss") : "无";
                return model;
            });
            result.count = coupons.TotalCount;

            return Json(result);
        }

        #endregion
    }
}